package com.gzq.tool.file.excel;

import com.gzq.tool.file.AbstractCellInfo;
import com.gzq.tool.file.AbstractFileToPojoFactory;
import com.gzq.tool.file.FileInfo;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ExcelToPojoFactoryAbstract<T> implements AbstractFileToPojoFactory {

    @Override
    public List<T> createPojos(FileInfo fileInfo, Class c) throws IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(new File(fileInfo.getFilePath()));
            Sheet sheet = workbook.getSheet(fileInfo.getsheetName());
            int lastRowNum = sheet.getLastRowNum();

            List<AbstractCellInfo> cellInfoList = fileInfo.listCellInfo();

            Row row = null;
            Cell cell = null;
            List<T> list = new ArrayList<>();
            for (int i = fileInfo.getStartRow(); i < lastRowNum; i++) {
                T t = (T) c.newInstance();
                row = sheet.getRow(i);

                if (cellInfoList == null) {
                    System.out.println("annotation");
                }else {
                    for (int j = 0; j < cellInfoList.size(); j++) {
                        cell = row.getCell(j);
                        AbstractCellInfo cellInfo = cellInfoList.get(j);
                        setFiledValue(cellInfo,t,cell);
                    }
                }

                list.add(t);

            }
        }finally {
            if (workbook != null) {
                workbook.close();
            }
        }




        return null;
    }




    private void setFiledValue(AbstractCellInfo cellInfo, T t, Cell cell) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Method method = t.getClass().getMethod("get" + cellInfo.getPojoFiledName(), null);
        Class<?> returnType = method.getReturnType();

        String obj = null;
        if (returnType == String.class){
            obj = cell.getStringCellValue();
        }


        double numericCellValue = cell.getNumericCellValue();

        if (t instanceof List){

        }

        method.invoke(t,obj);


    }

}
